import React, { Component } from 'react';
import { toJS } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import QueueAnim from 'rc-queue-anim';
import { Icon, SearchBar, Tools, Popover, Avatar, Picker, ActionSheet, Modal } from 'weaver-mobile';
import { ListViewPage, SearchPage } from 'weaver-mobile-page';

import Api from '../../apis/contacts';

import New from '../new/New';
import NavBar from '../widget/NavBar';
import ActionButtons from '../widget/ActionButtons';
import AddContact from './addContact';
import PersonCard from './personCard';

const { Item } = Popover;
const { getLabel } = Tools;
const { alert } = Modal;

const ActionBtns = [
  {key: 'write', title: getLabel('30912', '写信'), icon: 'bianji'},
  {key: 'move', title: getLabel('81298', '移动到'), icon: 'blog-yidong'},
  {key: 'copy', title: getLabel('383953', '复制到'), icon: 'blog-fuzhi'},
  {key: 'more', title: getLabel('17499', '更多'), icon: 'ellipsis'},
];

@inject('contactStore')
@inject('addContactStore')
@withRouter
@observer
export default class Contacts extends Component {
  static defaultProps = {
    prefixCls: "email-contact",
  };

  componentDidMount() {
    const { contactStore } = this.props;
    const { listViewStore, template } = contactStore;
    contactStore.clear();
    listViewStore.selectNone();
    listViewStore.setState({ template });
    contactStore.getContactCountList();
  }

  componentWillUnmount() {
    ActionSheet.close();
  }

  getTemplate = () => {
    const newTemp = {
      default: [
        {
          key: 'col1',
          style: { flex: 'none' },
          render: (data) => {
            const { mailUserName } = data;
            return (<Avatar name={mailUserName ? mailUserName.toUpperCase()[0] : ''}  url=""/>);
          },
        },
        {
          key: 'col2',
          configs: [
            { key: 'row1', configs: [{ key: 'mailUserName' }] },
            { key: 'row2', configs: [{ key: 'mailaddress' }] },
          ],
        },
      ],
    };
    return newTemp;
  }

  onRowClick = (data) => {
    const { contactStore, contactStore:{ showCheck, routes: { personCard } }, history } = this.props;
    const { id, mailUserName, mailaddress } = data;
    if (showCheck) { return; }
    contactStore.setState({ mailContact: { id, mailUserName, mailaddress }, newParams: { to: mailaddress, isInternal: 0 } });
    history.push(personCard);
  }

  getSwipeActionProps = () => ({
    right: [
      {
        text: getLabel('17499', '更多'),
        onPress: this.showMoreActions,
        className: `${this.props.prefixCls}-more`,
      },
      {
        text: getLabel('30912', '写信'),
        onPress: (data) => {
          const { contactStore, contactStore: {routes: { writeNew } }, history } = this.props;
          const { mailaddress } = data;
          contactStore.setState({ newParams: { to: mailaddress, isInternal: 0 }});
          history.push(writeNew);
        },
        className: `${this.props.prefixCls}-write`,
      },
      {
        text: getLabel('91','删除'),
        onPress: (data) => {
          alert(getLabel('500261', '确定删除联系人?'), '', [
            { text: getLabel('31129', '取消') },
            { text: getLabel('826', '确定'), onPress: () => {
              const { id } = data;
              this.callContactOperation({ operation: 'deleteContact', concactIds: id, });
            }},
          ]);
        },
        className: `${this.props.prefixCls}-del`,
      },
    ],
  })

  getActionButtons = () => {
    const { history, contactStore, contactStore: { currentAction, routes: { writeNew }, listViewStore: { data, rowKey, selectedRowKeys } } } = this.props;
    const canAction = selectedRowKeys.length > 0;
    const doAction = (key) => {
      switch(key) {
        case 'write':
          let mailaddresses = data.filter(d => selectedRowKeys.indexOf(d[rowKey]) !== -1).map(d => d.mailaddress);
          contactStore.setState({ newParams: { to: mailaddresses, isInternal: 0 }, currentAction: '' });
          history.push(writeNew);
          break;
        case 'move':
          contactStore.setState({ opt: 'move', concactIds: selectedRowKeys, showPicker: true });
          break;
        case 'copy':
          contactStore.setState({ opt: 'copy', concactIds: selectedRowKeys, showPicker: true });
          break;
        case 'more':
          this.showMoreActions();
          break;
        default:
          break;
      }
    }
    let btns = ActionBtns.map(b => ({
      key: b.key,
      title: (<span className={canAction ? '' : 'disabled'}>{b.title}</span>),
      icon: (<Icon type={b.icon} className={canAction ? '' : 'disabled'} />),
      selectedIcon: (<Icon type={b.icon} className={canAction ? '' : 'disabled'} />),
      onPress: canAction ? () => {
        const key = b.key === currentAction ? '' : b.key;
        contactStore.setState({ currentAction: key });
        doAction(key);
      } : () => {}
    }));
    btns = btns.map(btn => ({ ...btn, selected: btn.key === currentAction }));
    return btns;
  }

  showMoreActions = (data) => {
    const { contactStore } = this.props;
    const { mailgroupid } = contactStore;
    let BUTTONS;
    let concactIds;
    if (data) {
      concactIds = [data.id];
      BUTTONS = [
        { content: getLabel('81298', '移动到'), onClick: () => {
          contactStore.setState({ opt: 'move', concactIds, showPicker: true });
        }},
        { content: getLabel('383953', '复制到'), onClick: () => {
          contactStore.setState({ opt: 'copy', concactIds, showPicker: true });
        }},
        { content: getLabel('31129', '取消') },
      ];
    } else {
      const { listViewStore: { selectedRowKeys } } = contactStore;
      concactIds = selectedRowKeys;
      BUTTONS = [
        { content: getLabel('91', '删除'), onClick: () =>
          alert(getLabel('500261', '确定删除联系人?'), '', [
            { text: getLabel('31129', '取消') },
            { text: getLabel('826', '确定'), onPress: () =>
              this.callContactOperation({ operation: 'deleteContact', concactIds, })
            },
          ])
        },
        { content: getLabel('31129', '取消'), onClick: () => {
          contactStore.setState({ currentAction: '' });
        } },
      ];
    }
    if (Number(mailgroupid) && Number(mailgroupid) !== -1 && Number(mailgroupid) !== 0) {
      BUTTONS.splice(0, 0, {
        content: getLabel('384341', '从该组移除'),
        onClick: () => {
          this.callContactOperation({ operation: 'deleteContactFromGourp', concactIds, sourceGroup: mailgroupid });
        }
      });
    }
    ActionSheet.showActionSheetWithOptions({
      options: BUTTONS,
      cancelButtonIndex: BUTTONS.length - 1,
      maskClosable: true,
      'data-seed': 'logId',
    });
  }

  callContactOperation = (params, resolve, reject) => {
    const { contactStore } = this.props;
    Api.contactOperation({ ...params })
      .then(res => {
        const { flag, status } = res;
        if ((flag !== undefined && flag) || status === '1') {
          contactStore.getContactCountList();
          contactStore.setState({ opt: '', currentAction:'', concactIds: [], showCheck: false });
          contactStore.listViewStore.selectNone();
          if (resolve) { resolve(); }
        } else {
          if (reject) { reject(res); }
        }
      });
  }

  onSearch = () => {
    const { contactStore } = this.props;
    const {
      searchParams,
      searchKey,
      localStorageKey,
    } = contactStore;
    contactStore.getListData();
    const currentValue = searchParams[searchKey] || '';
    if (currentValue) {
      let searchHistory = localStorage.getItem(localStorageKey);
      searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
      searchHistory = searchHistory.filter(h => h.key !== currentValue);
      searchHistory.unshift({ key: currentValue, name: currentValue });
      localStorage.setItem(localStorageKey, JSON.stringify(searchHistory));
    }
  }

  onSearchPageClear = () => {
    const { contactStore } = this.props;
    const { searchPageStore, localStorageKey } = contactStore;
    localStorage.removeItem(localStorageKey);
    searchPageStore.list.setState({ data: [] });
  }

  onSearchPageChange = (v) => {
    const { contactStore } = this.props;
    const { searchParams, searchKey } = contactStore;
    contactStore.setState({ searchParams: {...searchParams, [searchKey]: v } });
  }

  onAddContact = (contact) => {
    const { addContactStore, contactStore, history } = this.props;
    const { form } = addContactStore;
    const { routes: { addContact, personCardAddContact } } = contactStore;
    const params = { id: '', mailUserName: '', mailAddress: '', ...contact };
    form.resetFields();
    addContactStore.clear();
    Api.contactCondition({ ...params })
    .then(res => {
      const { conditions, mailContact } = res;
      const conditioninfo = addContactStore.handleCondition(conditions);
      const route = contact ? personCardAddContact : addContact;
      form.initForm(conditioninfo, `${route}/form`);
      const checkedGroups = mailContact.groups.map(group => group.mailGroupId);
      addContactStore.setState({ mailContact: params, conditions: conditioninfo , checkedGroups });
      if (contact) {
        const formValues = {};
        Object.keys(mailContact).forEach(domkey => {
          formValues[domkey] = { value: mailContact[domkey] };
        });
        form.updateFields(formValues);
      }
      history.push(route);
    });
  } 

  render() {
    const { contactStore, history, prefixCls } = this.props;
    const {
      mailContact,
      showCheck,
      showPopover,
      showPicker,
      listViewStore,
      listViewStore: { selectedRowKeys, isSelectedAll },
      searchPageStore,
      searchParams,
      searchKey,
      routes: { searchPage, personCard, writeNew },
      localStorageKey,
      sysGroups,
      userGroups,
      mailgroupid,
      newParams,
      concactIds,
    } = contactStore;
    const mailgroups = [ ...(concactIds.length > 0 ? [] : sysGroups), ...userGroups ].map(g => ({
      ...g,
      // label: `${g.groupName}(${g.count})`,
      label: <div style={{display: 'flex', justifyContent: 'center'}}><span style={{overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis"}}>{g.groupName}</span><span style={{flexShrink: '0'}}>({g.count})</span></div>,
      value: g.goutId,
    }));
    const mailgroupValue = toJS([...sysGroups, ...userGroups]).find(k => k.goutId === mailgroupid);
    return (
      <QueueAnim>
        <div className={`${prefixCls} wm-route-layout`} key="email-contacts">
          <SearchPage
            searchValue={searchParams[searchKey] || ''}
            store={searchPageStore}
            rowKey="key"
            nameKey="name"
            type={1}
            onChange={this.onSearchPageChange}
            onSubmit={(v) => {
              this.onSearchPageChange(v);
              this.onSearch();
            }}
            onClear={this.onSearchPageClear}
          />
          <SearchBar
            className="search-select"
            placeholder={getLabel('510978', '请输入联系人姓名、邮件、手机')}
            value={searchParams[searchKey] || ''}
            showExtraButton
            extraButton={[
              { key: 'popover', show:
              <Popover
                mask
                visible={showPopover}
                overlay={[<Item key="add">{getLabel('19956', '添加联系人')}</Item>, <Item key="all">{getLabel('500410', '批量操作')}</Item>]}
                onSelect={item => {
                  item.key === 'add' ? this.onAddContact() : contactStore.setState({ showCheck: true });
                  contactStore.setState({ showPopover: false });
                }}
                onVisibleChange={v => contactStore.setState({ showPopover: v })}
              >
                <Icon type="ellipsis" />
              </Popover>
              },
            ]}
            onFocus={() => {
              history.push(searchPage);
              const key = localStorageKey;
              let searchHistory = localStorage.getItem(key);
              searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
              searchPageStore.list.setState({ data: searchHistory });
            }}
          />
          <Picker
            visible={showPicker}
            data={mailgroups}
            cols={1}
            value={[mailgroupid]}
            onOk={(v) => {
              const { opt } = contactStore;
              let newState = { showPicker: false };
              if (opt) {
                contactStore.setState(newState);
                this.callContactOperation({ operation: 'moveOrCopyToGroup', opt, concactIds, groupId: v[0] });
              } else {
                newState = { ...newState, mailgroupid: v[0], showCheck: false };
                contactStore.setState(newState);
                listViewStore.selectNone();
                contactStore.getListData(1);
              }
            }}
            onDismiss={() => contactStore.setState({ opt: '', currentAction:'', concactIds: [], showPicker: false })}
          />
          <div className={`${prefixCls}-group-wrapper`} onClick={() => contactStore.setState({ showPicker: true })}>
            <div className={`${prefixCls}-group`}>
              <div className={`${prefixCls}-group-label`}>
                <div className={`${prefixCls}-group-name`}>
                  <span className='name'>{mailgroupValue && `${mailgroupValue.groupName}`}</span>
                  <span className='count'>{mailgroupValue && `(${mailgroupValue.count})`}</span>
                </div>
                <span className={`${prefixCls}-group-icon`}><Icon type="jiantou-down" /></span>
              </div>
            </div>
          </div>
          {showCheck ? (<div className={`${prefixCls}-all am-list-item`}>
                <span className={`${prefixCls}-all-choise`}>
                  <span
                    className={`${prefixCls}-all-cancel`}
                    onClick={() => {contactStore.setState({ showCheck: false }); listViewStore.selectNone();}}
                  >{getLabel(31129, '取消')}</span>
                  <span>{`${getLabel(31503, '已选择')}${selectedRowKeys.length} ${getLabel('500260', '个联系人')}`}</span>
                </span>
                <span
                  className={`${prefixCls}-all-select`}
                  onClick={() => (isSelectedAll ? listViewStore.selectNone() : listViewStore.selectAll())}
                >
                  {`${isSelectedAll ? getLabel(31129, '取消') : ''}${getLabel(556, '全选')}`}
                </span>
              </div>) : null}
          <div className={`${prefixCls}-list-view`}>
            <ListViewPage.Normal
              className={`${prefixCls}-list ${showCheck ? 'showCheck' : ''}`}
              showCheck={showCheck}
              store={listViewStore}
              getDataCustom={true}
              customHeight="100%"
              withSwipeAction
              swipeActionProps={this.getSwipeActionProps()}
              getTemplate={this.getTemplate}
              onEndReached={contactStore.getListData}
              onRefresh={contactStore.getListData}
              onRowClick={this.onRowClick}
            />
          </div>
          {showCheck ? <ActionButtons data={this.getActionButtons()} /> : <NavBar onSelect={() => {
            contactStore.setState({ newParams: {} });
            history.push(writeNew);
            }} />}
          <Route
            key="addContact"
            path="/**/addContact"
            // component={AddContact}
            render={() => <AddContact title={getLabel('31229', '编辑联系人')}/>}
          />
          <Route
            key="personCard"
            path={personCard}
            render={() => (<PersonCard person={mailContact} extraActions={[{
              icon: 'mail-contact-person',
              label: getLabel('31229', '编辑联系人'),
              action: () => this.onAddContact(mailContact),
            }]} />)}
          />
          <Route
            key="new"
            path={writeNew}
            render={() => (<New path={writeNew} params={newParams}/>)}
          />
        </div>
      </QueueAnim>
    );
  }
}